package me.xue.communityhealth.admin.controller;

import me.xue.communityhealth.model.DrugPlace;
import me.xue.communityhealth.service.DrugPlaceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Controller
public class DrugPlaceController {

    private final DrugPlaceService service;

    @Autowired
    public DrugPlaceController(DrugPlaceService service) {
        this.service = service;
    }

    @GetMapping("/drugPlaces")
    public String all(Model model) {
        List<DrugPlace> drugPlaces = service.findAll();
        model.addAttribute("drugPlaces", drugPlaces);
        return "drug_places";
    }

    @GetMapping("/drugPlace/add")
    public String addPage(Model model) {
        model.addAttribute("drugPlace", new DrugPlace());
        return "drug_place_edit";
    }

    @PostMapping("/drugPlace")
    public String add(DrugPlace drugPlace) {
        if (service.save(drugPlace) == 1) {
            return "redirect:/drugPlaces";
        }
        return "drug_place_edit";
    }

    @DeleteMapping("/drugPlace/{id:\\d+}")
    @ResponseBody
    public String delete(@PathVariable("id") Integer id) {
        if (service.delete(id) == 1) {
            return "success";
        }
        return "fail";
    }

    @GetMapping("/drugPlace/{id:\\d+}/edit")
    public String updatePage(@PathVariable("id") Integer id, Model model) {
        DrugPlace drugPlace = service.findOne(id);
        model.addAttribute("drugPlace", drugPlace);
        return "drug_place_edit";
    }

    @PutMapping("/drugPlace")
    public String update(DrugPlace drugPlace) {
        if (service.update(drugPlace) == 1) {
            return "redirect:/drugPlaces";
        }
        return "drug_place_edit";
    }
    
}
